package com.azhon.basic.utils;

import android.app.Activity;
import android.os.Process;

import java.util.ArrayList;
import java.util.List;


public class ActivityManagerUtils {
    private List<Activity> activityList = new ArrayList<>();
    private static ActivityManagerUtils instance;
    
    // 单例模式中获取唯一的ExitApplication实例
    public static synchronized ActivityManagerUtils getInstance() {
        if (null == instance) {
            instance = new ActivityManagerUtils();
        }
        return instance;
    }
    
    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        if (activityList == null){
            activityList = new ArrayList<>();
        }
        activityList.add(activity);
    }
    
    public Activity getTopActivity() {
        if (activityList.isEmpty()) {
            return null;
        } else {
            return activityList.get(activityList.size() - 1);
        }
    }
    
    // 移除Activity
    public void removeActivity(Activity activity) {
        if (activityList != null) {
            activityList.remove(activity);
        }
    }
    
    // 遍历所有Activity并finish
    public void exitSystem() {
        for (Activity activity : activityList) {
            if (activity != null) {
                activity.finish();
            }
        }
        // 退出进程
        Process.killProcess(Process.myPid());
//        System.exit(0);
    }
    
    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityList.get(activityList.size() - 1);
        finishActivity(activity);
    }
    
    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityList.remove(activity);
            activity.finish();
            activity = null;
        }
    }
    
    // 遍历所有Activity并finish
    public void exitAllActivity() {
        for (Activity activity : activityList) {
            if (activity != null) {
                activity.finish();
            }
        }
    }

    public void exitOtherActivity() {
        for (int i = 0; i < activityList.size() - 1; i++) {
            Activity activity = activityList.get(i);
            if (activity != null) {
                activity.finish();
            }
        }
    }
}
